const superagent = require('superagent');
const cheerio = require('cheerio');
const config = require('./js/config');
const getCode = require('./js/getCode');
const getLogin = require('./js/login');
const jm = require('./js/jm');
const readline = require('readline-sync');
const events = require('events');
const myEmitter = new events.EventEmitter();

let loginParameter = {};
const { userInfo } = config;
const getCodeFn = (cookie, data = loginParameter) => {
  getCode(cookie)
    .then((codeData) => {
      const loginData = {
        yzm: codeData,
        __VIEWSTATE: data.__VIEWSTATE || loginParameter.__VIEWSTATE,
        __VIEWSTATEGENERATOR: data.__VIEWSTATEGENERATOR || loginParameter.__VIEWSTATEGENERATOR,
        cookie: cookie,
      };
      // 触发登录
      myEmitter.emit('loginData', loginData);
    })
    .catch((err) => {
      console.log(err);
    });
};
const getLoginData = () => {
  getLogin().then((data) => {
    const cookie = data.cookie[0];
    getCodeFn(cookie, data);
  });
};
const loginFn = (data) => {
  return new Promise(res => {
  let { __VIEWSTATE, __VIEWSTATEGENERATOR, yzm, cookie } = data;
  const yzmnew = readline.question('验证码识别为' + yzm + '，是否使用:');
  if (yzmnew != yzm && yzmnew.length == 4) {
    yzm = yzmnew;
  }
  superagent
    .post(config.login)
    .send({ __VIEWSTATE, __VIEWSTATEGENERATOR, www: jm(userInfo.password), username: userInfo.username, yzm, chkRemember: 'on' })
    .set('content-type', 'application/x-www-form-urlencoded')
    .set('Cookie', cookie)
    .end((err, res) => {
      if (err) throw err;
      let $ = cheerio.load(res.text);
      const showError = res.text.match(/showError\(\'+.+,/g);
      const error = showError ? showError[0] : '';
      const title = $('.header-right .fonticoncolor').attr('title');
      if (error.includes('验证码不正确')) {
        getCodeFn(loginParameter.cookie);
      }
      if (title == '注销') {
        console.log('登录成功');
        res()
      }
    });
  })
};
// 监听登录传参是否有变化
myEmitter.on('loginData', (data) => {
  loginParameter = data;
  loginFn(data);
});
// 第一次执行请求登录页
getLoginData().then(){
  // 登录成功

}
